﻿/* SharePoint Console Project
 * Http://SharePointConsole.codeplex.com
 * Copyright Jean-Alain Baeyens (2009)
 * Software under Microsoft Reciprocal License (Ms-RL)
 */

using System;

using Microsoft.SharePoint;
using Microsoft.Office.Server.Search.Administration;
using Sharepoint.Console.Commands;

namespace Sharepoint.Console.Search
{
    class CreateCrawledProperty : BaseCommande
    {
        public override string ShortHelp
        {
            get
            {
                return "Create a new crawled property";
            }
        }

        public override string LongHelp
        {
            get
            {
                return "Creating a new crawled property is a interessing command when you must map this property corresponding to a new column because you don't wait that a crawl run.";
            }
        }


        public override string Syntax
        {
            get
            {
                return "CreateCrawledProperty [PropertyName] [PropertyType]";
            }
        }

        public override string Execute(string[] args)
        {
            if (args.Length != 3) return string.Format("Invalide syntax. Use {0}", Syntax);

            try
            {
                string propertyType = args[2];
                string propertyName = args[1];
                int variantType;
                if (! int.TryParse(propertyType, out variantType)) return "Invalid Variant Type";
                Guid propset = new Guid("00130329-0000-0130-c000-000000131346");

                Schema spSchema = new Schema(SearchContext.GetContext(this.SharepointConnection.Site));
                CategoryCollection  categories = spSchema.AllCategories;
                Category sharepointCategory = categories["SharePoint"];
                CrawledProperty cprop = sharepointCategory.CreateCrawledProperty(propertyName
                                                                , false, propset ,variantType);
                if (cprop == null)
                {
                    return "Creation failed";
                }
                else
                {
                    // Set IsMappedToContents property but actually it's without effect.
                    // Property must be reset after map or manually.
                    cprop.IsMappedToContents = true;
                    cprop.Update();
                    return "Crawled Property succefuly created";
                }
            }
            
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
